<template>
  <div>
    <!-- 顶部面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert title="添加商品信息" type="info" show-icon :closable="false"></el-alert>
      <!-- 进度条 -->
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab栏 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforLeave" @tab-click="tabClick">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称"  prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格"  prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量"  prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量"  prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader :options="cateList" 
              @change="changeCate"
              :props="cateProps"
              v-model="addForm.goods_cat"
              :show-all-levels="false"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in addForm.manyAttr" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border v-for="(cb,i) in item.attr_vals" :key="i" :label="cb"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in addForm.onlyAttr" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action表示图片上传到后台的api地址 -->
            <el-upload
              :headers="uploadobj"
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="addForm.fileList"
              :on-success="handleSuccess"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加按钮 -->
            <el-button type="primary" class="btnAdd" @click="add">添加</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

    </el-card>
    <!-- 预览图片弹出框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewDialogVisible"
      width="50%">
      <img :src="previewImg" alt="" width="100%">
    </el-dialog>
  </div>
</template>

<script>
//引入loadsh库
import _ from 'lodash'
export default {
  data() {
    return {
      //设置上传图片发送请求的请求头对象
      uploadobj: {
        Authorization: sessionStorage.getItem('token') || ''
      },
      //设置进度条被激活选项，默认进度条第一项被激活
      activeIndex: "0",
      //添加商品的表单数据
      addForm: {
        //商品名称
        goods_name: '',
        //商品价格
        goods_price: '',
        //商品重量
        goods_weight: '',
        //商品数量
        goods_number: '',
        //商品描述
        goods_introduce: '',
        //商品所属分类数组,存放商品每一级分类的id
        goods_cat: [],
        //商品的参数（数组），包含 动态参数 和 静态属性
        attrs: [],
        //选中项绑定值 即商品所属的分类
        // selectCate: [],
        //存放服务器返回的动态参数数据，many表示动态参数
        manyAttr: [],
        //存放服务器返回的静态属性数据，only表示静态属性
        onlyAttr: [],
        //上传的图片文件列表
        fileList: [],
        //上传图片的数组
        pics: []
      },
      //添加商品表单数据验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ]
      },
      //存放服务器返回的商品分类数据
      cateList: [],
      //级联选择器的显示数据
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      //上传图片的url地址
      uploadURL: 'https://www.liulongbin.top:8888/api/private/v1/upload',
      //控制预览图片对话框的显示和隐藏
      previewDialogVisible: false,
      //保存预览图片的url地址
      previewImg: ''
    };
  },
  created() {
    this.getCateList()
  },
  methods: {
    //获取所有商品分类数据
    async getCateList(){
      const {data: res} = await this.$http.get('categories')
      if(res.meta.status !== 200){
        return this.$message.error(res.meta.msg)
      }
      this.cateList = res.data
      // console.log(this.cateList);
    },
    //当级联选择器选中项发生变化时，会触发这个函数
    changeCate(){
      if(this.addForm.goods_cat.length !== 3){
        this.addForm.goods_cat = []
      }
    },
    //切换tab标签之前校验函数
    beforLeave(activeName, oldActiveName){
      if(oldActiveName === '0' && this.addForm.goods_cat.length !== 3){
        this.$message.error('请先选择商品分类，再进行下一步操作')
        return false
      }
    },
    //tab 被选中时触发
    async tabClick(){
      //选中tab栏‘商品参数’
      if(this.activeIndex === '1') {
        const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {sel: 'many'}
        })

        if(res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        res.data.forEach( item => {
          item.attr_vals= item.attr_vals.length == 0 ?  [] : item.attr_vals.split(' ')
        })

        this.addForm.manyAttr = res.data
        // console.log(this.addForm.manyAttr)
      } else if(this.activeIndex === '2') {
        const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {sel: 'only'}
        })
        if(res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.addForm.onlyAttr = res.data
      }
    },
    //处理图片预览效果
    handlePreview(file) {
      console.log(file);
      this.previewImg = file.response.data.url
      this.previewDialogVisible = true
    },
    //处理移除图片的操作
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      let i = this.addForm.pics.findIndex(function(item) {
        return item.pic === file.response.data.tmp_path
      })
      // 删除这个项
      this.addForm.pics.splice(i,1)
      console.log(this.addForm);
      
    },
    //监听图片上传成功的事件
    handleSuccess(response, file, fileList){
      let obj = {
        pics: response.data.tmp_path
      }
      this.addForm.pics.push(obj)
    },
    //添加商品
    add(){
      // console.log(this.addForm);
      this.$refs.addFormRef.validate(async (valid) => {
        if(!valid) {
          return this.$message.error('请先填写必要的表单项')
        }
        //执行添加的业务逻辑
        //用loadsh深拷贝addform转换为字符串
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')

        // form.attrs = []
        form.manyAttr.forEach(item => {
          let info = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.toString()
          }
          form.attrs.push(info)
        })
        form.onlyAttr.forEach(item => {
          let info = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          form.attrs.push(info)
        })

        delete form.fileList
        delete form.manyAttr
        delete form.onlyAttr
        
        const { data: res} = await this.$http.post('goods',form)
        if(res.meta.status !== 201){
          this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')
        // console.log(form);
        
      })
    }
  },
  computed: {
    //获取当前选中的商品第三级分类id
    cateId() {
      return this.addForm.goods_cat[2]
    }
  }
};
</script>

<style lang="less" scoped>
.el-steps {
  margin: 15px 0;
}
.el-checkbox {
  margin: 0 7px 0 0;
}
.btnAdd {
  margin-top: 15px;
}
</style>